//
//  YGMainViewController.swift
//  SwiftWebo
//
//  Created by 王勇 on 2018/5/26.
//  Copyright © 2018年 Brave. All rights reserved.
//

import UIKit
///主控制器
class YGMainViewController: UITabBarController {

    
    //定时器
    private var timer: Timer?
    
    // 编辑按钮
    lazy var composeButton:UIButton = {
      
        let composeBtn = UIButton()
        // 设置按钮图像
        composeBtn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
        composeBtn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted)
        composeBtn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
       composeBtn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted)
        
        return composeBtn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
        // 测试未读数量
        setupTimer()
//        YGNetworkManager.sharedManager.unreadCount()
        
        // 设置代理
          delegate = self
    }

    //MARK: - 监听方法
   @objc private func composeStates() {
        
     let vc = UIViewController()
     vc.view.backgroundColor = UIColor.red
     let nav = YGNavigationController(rootViewController: vc)
     self.present(nav, animated: true, completion: nil)
    }
    
    /*
     参数 portrait 是竖屏
     参数 landscape 横屏
     - 代码设置方向 ，可以在需要横屏时 单独处理
     - 设置方向后 当前控制器以及子控制器也会遵循这个方向
     - 如果播放视频 ，通常通过modal展现
     */
    
    /// 设置设备方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
       
        return .portrait
    }
    
    deinit {
        //释放定时器
        timer?.invalidate()
        
    }
    
}

// MARK: - 设置tabar代理
extension YGMainViewController:UITabBarControllerDelegate {
   
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        // 获取控制器在数组中索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        
        print("数组标识\(idx)---选中标识\(selectedIndex)")
        //点击第二次刷新首页 保证都为0再刷新 判断当前是首页索引 数组中也是首页索引
        if idx == 0 && idx == selectedIndex {
           
            print("点中首页")
            // 让首页控制器回到顶部 刷新数据
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! YGHomeViewController
            // 内容滚到最上
            vc.tableView?.setContentOffset(CGPoint.init(x: 0, y: -64), animated: true)
            // 加载数据
            vc.loadData()
    
        }
        
        //判断目标控制器是否是uiviewcontroller 是的话就不切换 防止中间加号按钮混乱
        return !viewController.isMember(of: UIViewController.self)
        
    }
}


// extension 类似oc分类，在swift中还可以用来切分代码
    //可以把相近的函数房子一个extension 中
    // 便于代码维护
    // 注意：与oc一样 extension 也不能自定义属性
// swift 分割写在本类 “}”的外面
// MARK: - 设置界面
extension YGMainViewController {
    
    /// 设置撰写按钮
    private func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        //计算按钮位置
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        composeButton.frame = tabBar.bounds.insetBy(dx: w * 2, dy: 0)
        // 添加事件
        composeButton.addTarget(self, action: #selector(composeStates), for: .touchUpInside)
    }
    
        /// 设置所有控制器
        private func setupChildControllers() {
    
            let array = [
                ["clsName":"YGHomeViewController","title":"首页","imageName":"tabbar_home"],["clsName":"YGMessageViewController","title":"消息","imageName":"tabbar_message_center"],
                ["clsName":"YGHomeViewController"],
                ["clsName":"YGDiscoverViewController","title":"发现","imageName":"tabbar_discover"],
                ["clsName":"YGMeViewController","title":"我的","imageName":"tabbar_profile"]
            ]
            
            var arrayClass = [UIViewController]()
            for dic in array {
                arrayClass.append(controller(dict: dic))
            }
            
            viewControllers = arrayClass
            
      
            
        }
        
        private func controller(dict:[String:String])->UIViewController {
            
            //获取字典数据
            guard let className = dict["clsName"],
                let title = dict["title"],
                let imageName = dict["imageName"],
             let cls = NSClassFromString(Bundle.main.namespace + "." + className) as? UIViewController.Type else {
                    
                    return UIViewController()
            }
            
             // 转换 字符串 转换class
            // 创建控制器
            let vc = cls.init()
            vc.title = title
            //设置tabbaritem 图片
            vc.tabBarItem.image = UIImage(named: imageName)
            vc.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
       
            //设置字体颜色
             vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.orange], for: .selected)
            //设置字体大小 默认12
            vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 13)], for: .normal)
            // 添加到导航
            let nav = YGNavigationController(rootViewController: vc)
            
            return nav
            
        }
    
   
}

// MARK: -时钟方法
extension YGMainViewController {
    
    ///定义时钟
    private func setupTimer() {
    
        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
    }
    
    
    /// 触发方法 请求
    @objc private func updateTimer(){
  
        YGNetworkManager.sharedManager.unreadCount { (count) in
           print("有\(count)条数据未读")
           
            
            //设置tabar的bagevalue值
            // 未读数据大于0 才显示
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" :nil
            
            // 设置 APP 的badgeValue 值 ios8 之后需要用户授权才显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    
    }
}


